package com.dolphin.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

/**
 * @author shida
 */
@Slf4j
public class JsonInterface {

    private JsonInterface(){}

    static {
        JSON.DEFAULT_GENERATE_FEATURE |= SerializerFeature.WriteMapNullValue.getMask();
    }

    public static <T> T json2Object(String jsonString, Class<T> clazz){
        try {
            return JSON.toJavaObject(JSON.parseObject(jsonString), clazz);
        }catch (Exception e){
            log.error(e.getMessage(), e);
        }

        return null;
    }

    public static <T> T json2Object(String jsonString, TypeReference<T> tr){
        try {
            return JSON.parseObject(jsonString, tr);
        }catch (Exception e){
            log.error(e.getMessage(), e);
        }

        return null;
    }

    public static String toJson(Object object){
        if(object == null){
            return null;
        }

        if(object.getClass().equals(String.class)){
            return (String) object;
        }

        return JSON.toJSONString(object, SerializerFeature.DisableCircularReferenceDetect);
    }

    public static JSONObject toJsonObject(Object object){
        JSONObject jsonObject = (JSONObject) JSON.toJSON(object);

        return jsonObject;
    }

    public static <T> T javaObject2JavaObject(Object object, Class<T> clazz){
        if(object == null){
            return null;
        }

        try{
            return JSON.parseObject(toJson(object), clazz);
        }catch (Exception e){
            log.error(e.getMessage(), e);
        }

        return null;
    }

    public static <T> List<T> jsonArr2List(JSONArray jsonArray, Class<T> clazz){
        try{
            return jsonArray.toJavaList(clazz);
        }catch (Exception e){
            log.error(e.getMessage(), e);
        }

        return Lists.newArrayList();
    }

    public static <T> List<T> jsonArr2ListByStr(String json, Class<T> clazz){
        try{
            JSONArray jsonArray = JSON.parseArray(json);
            return jsonArray.toJavaList(clazz);
        }catch (Exception e){
            log.error(e.getMessage(), e);
        }

        return Lists.newArrayList();
    }

    public static Map<String, Object> jsonObject2Map(String jsonObject){
        try{
            Map<String, Object> itemMap = JSONObject.parseObject(jsonObject, new TypeReference<Map<String, Object>>(){});

            return itemMap;
        }catch (Exception e){
            log.error(e.getMessage(), e);
        }

        return Maps.newHashMap();
    }
}
